#include "SGP30.h"




void sgp_init(void)
{
	IIC_Init();
}

void sgp_get_feature_set_version()
{
	s8 i,ret;
	u8 buf[3];
	
	buf[0] = 0x20;
	buf[1] = 0x2f;
	
	IIC_Start();
	
	IIC_WriteByte(SGP_ADDR);
	IIC_Wait_Ack();
	
	IIC_WriteByte(buf[0]);
	IIC_Wait_Ack();
	
	IIC_WriteByte(buf[1]);
	IIC_Wait_Ack();
	
	IIC_Stop();
	
	delay_ms(4);
	
	IIC_Start();
	
	IIC_WriteByte(SGP_ADDR | 0x1);
	
	IIC_Wait_Ack();
	
	IIC_DEBUG = 1;
	IIC_DEBUG = 0;
    buf[0] = IIC_ReadByte(1);
	IIC_DEBUG = 1;
	IIC_DEBUG = 0;
	buf[1] = IIC_ReadByte(1);
	IIC_DEBUG = 1;
	IIC_DEBUG = 0;
    buf[2] = IIC_ReadByte(0);
 
	IIC_Stop();
	
	printf("sgp_get_feature_set_version: \n");
	for(i=0;i<3;i++)
		printf(" 0x%02X",buf[i]);
	printf("\n");
	
}



u16 sgp_get_serial_id()
{
	s8 i,ret;
	u8 buf[6];
	
	buf[0] = 0x36;
	buf[1] = 0x82;
	
	IIC_Start();
	IIC_WriteByte(SGP_ADDR);
	IIC_Wait_Ack();
	IIC_WriteByte(buf[0]);
	IIC_Wait_Ack();
	IIC_WriteByte(buf[1]);
	IIC_Wait_Ack();
	IIC_Stop();
	
	delay_ms(1);
	
	IIC_Start();
	IIC_WriteByte(SGP_ADDR | 0x1);
	IIC_Wait_Ack();
	for (i = 0; i < 6; i++) {
        buf[i] = IIC_ReadByte(1);
    }
 
	IIC_Stop();
//	sgp_i2c_write(buf,2);
//	delay_ms(1);
//	sgp_i2c_read(buf,3);
//	
	printf("sgp_get_serial_id: \n");
	for(i=0;i<6;i++)
		printf(" 0x%02X",buf[i]);
	printf("\n");
	
	return 0;
}



void sgp_i2c_write(u8* dat,u8 len) 
{
	u8 i;
	u8 ret;
	
	IIC_Start();
	
	IIC_WriteByte(SGP_ADDR);
	
	ret = IIC_Wait_Ack();
	if(ret != 0)
	{
		printf("i2c write wait ack error!\n");
		return;
	}
	
    for (i = 0; i < len; i++) {
        IIC_WriteByte(dat[i]);
		
		ret = IIC_Wait_Ack();
		if(ret != 0)
		{
			printf("i2c write wait ack error %d!\n",i);
			return;
		}
    }
 
	//IIC_Stop();
}

void sgp_i2c_read(u8* dat,u8 len) 
{
	u8 i,ret;
	
	IIC_Start();
	
	IIC_WriteByte(SGP_ADDR | 0x1);
	
	ret = IIC_Wait_Ack();
	if(ret != 0)
	{
		printf("i2c read wait ack error!\n");
		return;
	}
	
    for (i = 0; i < len; i++) {
        dat[i] = IIC_ReadByte(1);
    }
 
	IIC_Stop();
}





